import React, { useRef, useState } from "react";
import { Button, Modal, Space, message } from "antd";
import { useRequest } from "ahooks";
import { PlusOutlined } from '@ant-design/icons';
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { destinaionTypes  } from "@/constants/types";
import { fetchDestinationList, addDestination, updateDestination, delDestination  } from "../services";
import DestUpdateModal from "../modals/DestUpdateModal";
import { useModel } from "@umijs/max";

const Destinaion = () => {
  const tableRef = useRef();
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<destinaionTypes | null>(null);
  const {loading: addLoading, runAsync: addApi} = useRequest(addDestination, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateDestination, {manual: true});
  const { getDict, getDictLabel } = useModel('dictModel');
  const countrys = getDict('country');
  const destTypes = getDict('destType');


  const destUpdateProps = {
    title: currentRow ? '修改目的地信息' : '新增目的地',
    visible,
    loading: addLoading || updateLoading,
    currentRow,
    onSubmit: async (params: destinaionTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
        tableRef?.current?.reload();
      }
    },
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    }
  }

  const handleAdd = () => {
    setVisible(true);
  }
  const handleEdit = (record: destinaionTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleDel = (record: destinaionTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定删除？',
      onOk: () => {
        delDestination({id: record.id}).then(res => {
          setVisible(false);
          setCurrentRow(null);
          tableRef?.current?.reload();
        })
      }
    });
  }

  const columns: ProColumnType<destinaionTypes> [] = [
    {
      title: '国家',
      hideInTable: true,
      dataIndex: 'country',
      valueType: 'select',
      fieldProps: {
        options: countrys
      }
    },
    {
      title: '国家',
      width: 80,
      search: false,
      dataIndex: 'countryName'
    },
    {
      title: '类型',
      width: 80,
      dataIndex: 'destType',
      valueType: 'select',
      fieldProps: {
        options: destTypes
      },
      render: (_, record) => <span>{getDictLabel('destType', record?.destType)}</span>
    },
    {
      title: 'Code',
      width: 120,
      dataIndex: 'destCode'
    },
    {
      title: '地址',
      search: false,
      dataIndex: 'address'
    },
    {
      title: 'City',
      search: false,
      dataIndex: 'city'
    },
    {
      title: 'State',
      search: false,
      dataIndex: 'state'
    },
    {
      title: 'Zip',
      search: false,
      dataIndex: 'zip'
    },
    {
      title: '创建时间',
      search: false,
      width: 150,
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      render: (_, record: destinaionTypes) => {
        return (
          <Space>
            <Button onClick={() => handleEdit(record)} type="link">编辑</Button>
            <Button onClick={() => handleDel(record)} type="link">删除</Button>
          </Space>
        );
      }
    }
  ];
  
  return (
    <> 
      <ProTable
        rowKey="id"
        bordered
        actionRef={tableRef}
        options={false}
        search={{span: 6}}
        columns={columns}
        toolBarRender={() => [
          <Button onClick={handleAdd} type="primary">
            <PlusOutlined />
            新增地址
          </Button>
        ]}
        scroll={{y: 400}}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchDestinationList({
            ...params,
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20,
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
      />
      {visible && <DestUpdateModal {...destUpdateProps} />}
    </>
  );
};


export default Destinaion;